/**
 * Created by Evan on 2018/3/16.
 * 常用函数封装
 */
const crypto = require('crypto');

const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const chars2 = 'abcdefghijklmnopqrstuvwxyz';
const chars3 = 'abcdefghijklmnopqrstuvwxyz0123456789';

module.exports = {
    isEmpty(str) {
        if (str == undefined || str == "" || str == null || str.length == 0) {
            return true;
        }
        return false;
    },
    distinct(arr) {
        let result = []
        let obj = {}
        for (let i of arr) {
            if (!obj[i]) {
                result.push(i)
                obj[i] = 1
            }
        }
        return result
    },
    inValid(str, max, min) {
        if (min == undefined || min == null || min == "")
            min = 1;
        if (str == undefined || str == "" || str == null || str.length < min || str.length > max) {
            return true;
        }
        return false;
    },
    md5(str) {
        return crypto.createHash('md5').update(str).digest('hex');
    },
    randomBytes(num) {
        let buf = crypto.randomBytes(num);
        let token = buf.toString('hex').substring(0, num);
        return token;
    },
    getUserIP(req) {
        let ip = req.headers['x-forwarded-for'] || req.ip ||
            req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress || '';
        if (ip != undefined && ip != null && ip.split(',').length > 0) {
            ip = ip.split(',')[0];
        }

        // console.log("ip1:"+ip);
        if (ip != undefined && ip != null) {
            if (ip.lastIndexOf(":") > 0 && ip.lastIndexOf(":") < ip.length) {
                ip = ip.substring(ip.lastIndexOf(":") + 1, ip.length);
            }
        } else {
            ip = "";
        }
        // console.log("ip2:"+ip);
        return ip;
    },
    guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    ipv4Check(ip) {
        if (ip == null)
            return false;
        if (!ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/))
            return false;
        let strArr = ip.split("."); //分割成数字数组
        for (let i = 0, len = strArr.length; i < len; i++) {
            let v = parseInt(strArr[i]);
            if (v < 0 || v > 255)
                return false;
        }
        return true;
    },
    //获取参数
    getReqData(ctx) {
        let reqData = {};
        Object.assign(reqData, ctx.query, ctx.request.body, ctx.params);
        return reqData;
    },
    getSalt(length) {
        length = length || 8;
        let salt = '';
        for (let x = 0; x < length; x++) {
            let i = Math.floor(Math.random() * chars.length);
            salt += chars.charAt(i);
        }
        return salt;
    },
    getRandomAppKind(length) {
        length = length || 8;
        let appKind = '';
        for (let x = 0; x < length; x++) {
            let i = Math.floor(Math.random() * chars2.length);
            appKind += chars2.charAt(i);
        }
        appKind = 'ibuger_' + appKind;
        return appKind;
    },
    getRandomGQCode(length) {
        length = length || 6;
        let GQCode = '';
        for (let x = 0; x < length; x++) {
            let i = Math.floor(Math.random() * chars3.length);
            GQCode += chars3.charAt(i);
        }
        return GQCode;
    },
    isNumber(num) {
        return !this.isEmpty(num) && !isNaN(num);
    },
    inValidNumber(num, max, min) {
        if (this.isEmpty(min)) min = 0;
        if (this.isNumber(num) && num <= max && num >= min) {
            return false;
        }
        return true;
    },
    getRandomSession(length) {
        length = length || 25;
        let session = '';
        for (let x = 0; x < length; x++) {
            let i = Math.floor(Math.random() * chars.length);
            session += chars.charAt(i);
        }
        return session;
    },
    //检测输入，只能是中文、英文、数字
    checkInput(s) {
        let reg = /^(\w|[\u4E00-\u9FA5]|\+|\-|\*)*$/;
        return !!s.match(reg);
    },
};
